package udes.assassin;

import java.util.ArrayList;
import java.util.List;

import udes.assassin.R;
import udes.assassin.server.api.ClientManager;
import udes.assassin.server.api.Message.Message;
import udes.assassin.server.api.Message.GameSelectionMessage.TotalDisconnectMessage;
import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.CountDownTimer;
import android.preference.PreferenceManager;
import android.provider.Settings.Secure;
import android.util.Log;
import android.widget.Toast;

public class AssassinApplication extends Application implements OnSharedPreferenceChangeListener, ClientManager {  

	private SharedPreferences mPrefs;
	private UpdateService mService;
	public MessageManager mCurrentManager;
	private Intent mServiceIntent;
	public List<Message> mIncomingMessageQueue;

	public void onCreate() {
		super.onCreate();
		mCurrentManager = null;
		mIncomingMessageQueue = new ArrayList<Message>();
		mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
		mPrefs.registerOnSharedPreferenceChangeListener(this);
		Log.d("AssassinApplication", "Request service creation");
		
		// This is use as the main ID for the server
      	Global.getInstance().mId = Secure.getString(getContentResolver(), Secure.ANDROID_ID);
		
      	// start a process with server
      	startServerConnection();
	}
		
	public void onTerminate(){
		// Let the server know we stop communication
		sendMessage(new TotalDisconnectMessage());
		
		super.onTerminate();
	}

	public synchronized void onSharedPreferenceChanged(SharedPreferences sharedPrefs, String key) {	
      	String username = sharedPrefs.getString("pref_username", getString(R.string.default_username));

      	if(key.equals("pref_username")){
      		if(username.isEmpty()){ // server cannot handle null name
      			stopServerConnection();
      			
	      		final Toast tag = Toast.makeText(getApplicationContext(), R.string.error_unknown_player, Toast.LENGTH_SHORT);
	      		tag.show();
	
	      		// This act as displaying a long toast
	      		new CountDownTimer(4000, 1000){
	      		    public void onTick(long millisUntilFinished) {tag.show();}
	      		    public void onFinish() {tag.show();}
	      		}.start();
      		}
      		else{
      			restartServerConnection();
      		}
      	}
      	
      	if(key.equals("pref_server_address") || key.equals("pref_server_port")){ // is server port
      		restartServerConnection();
      	}
	}

	
	public void restartServerConnection(){
		stopServerConnection();
		startServerConnection();
	}
	
	public void startServerConnection(){
  		mServiceIntent = new Intent();
  		mServiceIntent.setAction(".UpdateService");
		startService(mServiceIntent);
	}
	
	public void stopServerConnection(){
		mService.Kill();
		mService.stopSelf();
		stopService(new Intent(this, UpdateService.class));
		Log.d("STOP SERVICE", "STOPPING SERVICES");
  		Global.getInstance().mIsConnectToServer = false;
		stopService(mServiceIntent);
	}
	
	public String getCurrentTopActivity() {
        ActivityManager mActivityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> RunningTask = mActivityManager.getRunningTasks(1);
        ActivityManager.RunningTaskInfo ar = RunningTask.get(0);
        return ar.topActivity.getClassName();
    }

	public void setService(UpdateService aUpdateService) {
		mService = aUpdateService;
	}
	
	public void sendMessage(Message aMessage){
		mService.getClient().SendMessage(aMessage);
	}

	public void ManageMessage(Message aMessage) {
		
		synchronized (mIncomingMessageQueue) {
			Log.d("Messaing :: " , "Received :: " + aMessage.getClass().getSimpleName());
			mIncomingMessageQueue.add(aMessage);
		}
	}
}
